#define PLUGIN_VERSION "1.0"

#include <sourcemod>
#include <l4d_lib>

#define ADD_BOT		"sb_add"

public Plugin:myinfo =
{
	name = "Spec Kick Bots Fix",
	author = "raziEiL [disawar1]",
	description = "Fixed no Survivor bots issue.",
	version = PLUGIN_VERSION,
	url = "http://steamcommunity.com/id/raziEiL"
}

static	Handle:g_hSurvivorLimit, g_iCvarSurvLimit, bool:bTempBlock;

public OnPluginStart()
{
	g_hSurvivorLimit = FindConVar("survivor_limit");

	HookConVarChange(g_hSurvivorLimit, OnCvarChange_SurvivorLimit);
	g_iCvarSurvLimit = GetConVarInt(g_hSurvivorLimit);

	HookEvent("player_team", SF_ev_PlayerTeam);

	RegAdminCmd("sm_botfix", CmdBotFix, ADMFLAG_ROOT);
}

public Action:CmdBotFix(client, args)
{
	SF_Fix();
	ReplyToCommand(client, "Checking complete.");
	return Plugin_Handled;
}

public OnMapStart()
{
	bTempBlock = false;
}

public Action:SF_ev_PlayerTeam(Handle:event, String:event_name[], bool:dontBroadcast)
{
	if (bTempBlock) return;

	new client = GetClientOfUserId(GetEventInt(event, "userid"));

	if (client && !IsFakeClient(client)){

		if (!GetEventBool(event, "disconnect") && GetEventInt(event, "team") == 1){

			bTempBlock = true;
			CreateTimer(1.0, SF_t_CheckBots);
		}
	}
}

public Action:SF_t_CheckBots(Handle:timer)
{
	SF_Fix();
}

SF_Fix()
{
	new iSurvivorCount;

	for (new i = 1; i <= MaxClients; i++)
		if (IsClientInGame(i) && GetClientTeam(i) == 2)
			iSurvivorCount++;

	if (iSurvivorCount < g_iCvarSurvLimit){

		static iFlag;

		if (!iFlag)
			iFlag = GetCommandFlags(ADD_BOT);

		SetCommandFlags(ADD_BOT, iFlag & ~FCVAR_CHEAT)

		while (iSurvivorCount != g_iCvarSurvLimit){

			ServerCommand(ADD_BOT);
			iSurvivorCount++;

			LogMessage("Bug detected. Trying to add a bot %d/%d", iSurvivorCount, g_iCvarSurvLimit);
		}

		SetCommandFlags(ADD_BOT, iFlag);
	}
}

public OnCvarChange_SurvivorLimit(Handle:hHandle, const String:sOldVal[], const String:sNewVal[])
{
	if (!StrEqual(sOldVal, sNewVal))
		g_iCvarSurvLimit = StringToInt(sNewVal);
}
